<template>
  <!-- 主页配置区域 -->
  <div class="portal-setting">
    <div class="portal-setting-box">
      <div class="portal-setting-header" v-if="isHavePortalPageSetAuth()">
        <div class="portal-setting-title mb_12">{{ $t('portal.portalInformation') }}</div>
        <div class="portal-setting-header-row">
          <span class="portal-setting-header-row-label mr_12">{{ $t('portal.portalName') }}：</span>
          <div class="portal-setting-header-row-name">
            {{ zh_CN_NAME }}
          </div>
          <i
            class="iconfont icon-edit-fill ml_8"
            @click="showDialog(editTemplateNameDialog)"
          ></i>
        </div>
        <div class="portal-setting-header-row top" v-if="isMultiLanguage">
          <div class="portal-setting-header-flex" >
            <span class="portal-setting-header-row-label ">{{ $t('portal.multilingual') }}</span>
            <el-tooltip
              class="portal-setting-header-row-margin"
              effect="dark"
              :content="$t('portal.portalTip6')"
              placement="top"
            >
              <i class="iconfont icon-fdn-info">：</i>
            </el-tooltip>
          </div>
          <div class="portal-setting-header-row-language">
            <span
              v-for="(v, i) in defaultLanguageSelectList"
              :key="v.code"
              :label="v.code"
              :disabled="v.isMainLanguage"
            >
              {{v.languageValue}}
            </span>
          </div>
        </div>

        <div class="portal-setting-header-row" v-if="isMultiLanguage">
          <span class="portal-setting-header-row-label mr_12">{{ $t('portal.wxSet.defaultLanguage') }}：</span>
          <el-dropdown :value="defaultLanguage" @command="defaultLanguageHandleCommand">
            <span :style="{marginRight: 8 + 'px'}">{{ defaultLanguage | filterNames}}</span>
            <i class="el-icon-arrow-down"></i>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="item in defaultLanguageSelectList" :key="item.code" :command="item.code"
                :divided="item.divided">
                {{ item.languageValue }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>

        <div class="portal-setting-header-row" v-if="portalAuth.doorSwitch">
          <span class="portal-setting-header-row-label mr_12">{{ $t('portal.portalState') }}：</span>
          <el-switch
            v-model="isIssued"
            @change="handerChange"
            :active-value="0"
            :inactive-value="1"
            :active-text="isIssued===0 ? $t('portal.inUse') : $t('common.customer.questionnaire.deactivated')"
          ></el-switch>
          <span class="portal-setting-header-row-tip ml_8">
            （{{ $t('portal.portalTip7') }}）
          </span>
        </div>
      </div>

      <div class="portal-setting-main mar-t-10">
        <!-- 快速分享 -->
        <div class="portal-setting-main-view">
          <div class="portal-setting-main-view-title mb_12">
            <div>{{ $t('portal.quickShare') }}</div>
            <div @click="changeUrl">
              <i class="iconfont icon-yindao"></i>
              <span>{{$t('portal.speedPortal')}}</span>
            </div>
          </div>
          <div>
            <div class="portal-setting-main-view-share">
              <div class="code-wrap">
                <div class="code-wrap-web">{{ $t('portal.web') }}：</div>
                <!-- 普通二维码 -->
                <div class="code-wrap-item">
                  <div id="qrcodeImg" ref="qrcodeImg"></div>
                  <div
                    id="downloadQrcodeImg"
                    ref="downloadQrcodeImg"
                    style="position: absolute; right: 0; top: 0; z-index: -100"
                  ></div>
                  <div class="mask-wrap">
                    <el-button
                      class="share-qrcodeImg-button"
                      type="default"
                      @click="downloadQrcode"
                    >
                      {{ $t('common.base.download') }}
                    </el-button>
                  </div>
                </div>
              </div>
              <div class="code-wrap" v-if="appletCodeUrl">
                <div class="code-wrap-miniApp">{{ $t('portal.miniApp') }}：</div>
                <!-- 小程序二维码 -->
                <div  class="code-wrap-item code-wrap-item-mini">
                  <img :src="appletCodeUrl" alt="">
                  <div class="mask-wrap">
                    <el-button
                      class="share-qrcodeImg-button"
                      type="default"
                      @click="downloadMiniQrcode"
                    >
                      {{ $t('common.base.download') }}
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
            <div class="portal-setting-main-view-link">
              <span class="portal-setting-main-view-label">
                {{ $t('portal.linkSharing') }}：
              </span>
              <div class="portal-setting-main-view-link-inputAndBtn">
                <div class="short-url-setting mar-b-8">
                  <span class="portal-setting-header-row-label mar-r-5">{{ $t('portal.useShortUrl') }}</span>
                  <el-switch
                    v-model="isUseShortUrl"
                    @change="handleUseShortUrl"
                    :active-value="1"
                    :inactive-value="0"
                  ></el-switch>
                </div>
                <el-input class="share-link" readonly v-model="shareLinkUrl">
                  <el-button
                    class="share-setting-copy"
                    type="primary"
                    slot="append"
                    @click="handleClickCopyShareUrl"
                    :data-clipboard-text="shareLinkUrl"
                  >
                  {{ $t('common.base.copy') }}
                  </el-button>
                </el-input>
              </div>
            </div>
            <div class="portal-setting-main-view-poster">
              <span class="portal-setting-main-view-label">{{ $t('portal.posterSharing') }}：</span>
              <!-- <el-button
                class="portal-setting-main-view-poster-download"
                type="default"
                @click="downloadPoster"
              >
              {{ $t('portal.posterDownload') }}
              </el-button> -->
              <span
                class="portal-setting-main-view-poster-preview"
                @click="showDialog(shareDialog)"
              >
              {{ $t('portal.generalPoster') }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分享弹框 -->
    <ShareDialog
      ref="shareDialog"
      :share-link="shareLink"
      :tenant-id="tenantId"
      :portal-auth="portalAuth"
      :door-type-id="doorTypeId"
      :appletCodeUrl="appletCodeUrl"
    />

    <!-- 门户名称编辑弹窗 -->
    <EditTemplateNameDialog
      ref="editTemplateNameDialog"
      :door-type="doorType"
      :title="$t('portal.portalName')"
      @callBack="updateDoorTypeName"
      :systemLanguage="language"
      :check-list="checkList"
      :language="language"
    />

    <!-- 设置弹窗暂不使用 -->
    <!-- <SettingDialog ref="settingDialog" title="门户设置" /> -->
  </div>
</template>

<script>
/** vue */
import {
  reactive,
  ref,
  toRefs,
  onMounted,
  computed,
  inject,
} from 'vue';
import ShareDialog from '@src/modules/portal/components/shareDialog.vue';
import EditTemplateNameDialog from '@src/modules/portal/components/EditTemplateNameDialog.vue';

/* api */
import { downloadDoorPosterV2, getShortLink, queryDoorAppletCode } from '@src/api/PortalApi.ts';

/* hooks */
import { setClipboardData } from '@src/util/dom'

/* util */
import QRCode from 'qrcodejs2';
import html2canvas from 'html2canvas';
import { Message } from 'element-ui';
import { isDevelopment } from '@src/util/platform';
import i18n from '@src/locales';
import { downloadImagesDirectly } from '@src/util/index.ts';
import { isHavePortalPageSetAuth } from '@service/AuthService'
export default {
  name: 'portal-setting',
  components: {
    ShareDialog,
    EditTemplateNameDialog,
  },
  filters: {
    filterNames(name) {
      const doorNameLanguage = {
        zh: '简体中文',
        en: 'English',
        ru: 'Русский язык',
        ja: '日本語',
        ko: '한국어'
      }
      return doorNameLanguage[name]
    }
  },
  props: {
    doorType: {
      type: Object,
      default: () => ({}),
    },
    portalAuth: {
      type: Object,
      default: () => ({}),
    },
    tenantId: {
      type: String,
      default: '',
    },
  },
  setup(props,{emit}) {
    const editDoorType = inject('editDoorType');

    const isMultiLanguage = inject('isMultiLanguage')

    const languagesList = inject('languagesList')
    console.log("languagesList",);

    const isDoorApplet = inject('isDoorApplet')

    const multiLanguageRef = ref(null)

    const qrcodeImg = ref(null);

    const downloadQrcodeImg = ref(null);

    const shareDialog = ref(null);

    const settingDialog = ref(null);

    const editTemplateNameDialog = ref(null);

    const languageType  = ref('zh')

    const doorTypeId = computed(() => props.doorType?.id ?? '');

    const isNoDefaultTemplate = computed(() => props.doorType?.defaultType === 1);

    const zh_CN_NAME = computed(() => {
      let zh_CN_NAME = props?.doorType?.zh_CN_NAME ?? '';
      zh_CN_NAME = zh_CN_NAME.length > 14
        ? `${zh_CN_NAME.substring(0, 14)}...`
        : zh_CN_NAME;
      return zh_CN_NAME;
    });

    const state = reactive({
      isIssued: 1, // 0启用，1禁用
      isUseShortUrl: 0,
      shareLink: '',
      shortShareLink: '',
      checkList: [],
      language:languagesList.value,
      appletCodeUrl: '',
    });

    const shareLinkUrl = computed(() => {
      if (state.isUseShortUrl) return state.shortShareLink
      return state.shareLink
    })

    // 默认语言下拉列表
    const defaultLanguageSelectList = computed(() => {
      return languagesList.value.filter((item) => state.checkList.find((v) => v === item.code));
    });

    const defaultLanguage = computed(() => {
      return props?.doorType?.setting?.defaultLanguage ?? 'zh'
    })
    // 筛选掉没开灰度的语言
    // if(!isMultiLanguage.value){
    //   state.language = [state.language[0]]
    // }
    // 因为之前有老数据创建的时候可能没有选择toB的语言
    const selectList = props?.doorType?.setting?.language.map(v=>v.code)
    const defalutList = languagesList.value.filter(item => item.isMainLanguage || item.isToB).map(v=>v.code)
    const allList = [...defalutList, ...selectList]
    state.checkList = [...new Set(allList)]
    const handerChange = async e => {
      const params = {
        inUse: state.isIssued,
        id: doorTypeId.value,
      };
      editDoorType({ editType: 'update', params });
    };

    const handleJumpSetting = () => {
      const resourcePrefix = isDevelopment() ? '' : '/shb/home';
      window.location.href = `${resourcePrefix}/portal/getDoorConfigPage?id=${doorTypeId.value}`;
    };

    const showDialog = vm => {
      vm.openDialog();
    };

    const changeUrl = () => {
      const url = 'https://www.yuque.com/shb/dry_goods/gefptxayhouklypw'
      window.open(url,'_blank')
    }

    const getQrcodeImg = shareLink => {
      new QRCode('qrcodeImg', {
        width: 110,
        height: 110,
        text: shareLink,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H,
      });

      // 供下载不失真使用
      new QRCode('downloadQrcodeImg', {
        width: 320,
        height: 320,
        text: shareLink,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H,
      });
    };

    const getShortShareLink = () => { 
      getShortLink({
        protalUrl: state.shareLink
      }).then(res => {
        state.shortShareLink = res.data || state.shareLink;
      })
    };

    const getInitData = async () => {
      state.isIssued = props.doorType.inUse;
      state.isUseShortUrl = props.doorType.setting.isUseShortUrl;
      state.shareLink = props.doorType.setting.protalUrl;
      getQrcodeImg(state.shareLink);
      getShortShareLink();
      isDoorApplet.value && getDoorAppletCode();
    };

    const handleClickCopyShareUrl = () => {
      setClipboardData(
        shareLinkUrl.value,
        ()=>{
          Message.success(i18n.t('common.modal.COPY_SUCCESS'));
        },
        ()=>{
          Message.error(i18n.t('common.base.tip.copyFail'));
        }
      )
    }

    // base64转blob
    const base64ToBlob = code => {
      let parts = code.split(';base64,');
      let contentType = parts[0].split(':')[1];
      let raw = window.atob(parts[1]);
      let ranLength = raw.length;

      let uint8Array = new Uint8Array(ranLength);

      for (let i = 0; i < ranLength; ++i) {
        uint8Array[i] = raw.charCodeAt(i);
      }

      return new Blob([uint8Array], { type: contentType });
    };

    const downloadPoster = async () => {
      try {
        const { code } = await downloadDoorPosterV2({
          codePath: state.shareLink,
          typeId: doorTypeId.value,
        });
        if (!code) return;

        let a = document.createElement('a');
        let event = new MouseEvent('click');
        const blob = base64ToBlob(code);
        const blobUrl = window.URL.createObjectURL(blob);

        a.href = blobUrl;
        a.setAttribute('download', `${i18n.t('portal.portalPoster')}.png`);
        a.dispatchEvent(event);
      } catch (error) {
        console.error('downloadPoster error', error);
      }
    };

    const downloadQrcode = () => {
      let domCanvas = downloadQrcodeImg.value;
      let width = domCanvas.scrollWidth;
      let height = domCanvas.scrollHeight;
      let scale = 1;
      html2canvas(domCanvas, {
        scale, // 放大倍数
        width,
        height,
        useCORS: true, // 开启跨域配置
      })
        .then(canvas => {
          let a = document.createElement('a');
          let event = new MouseEvent('click');
          a.href = canvas.toDataURL('image/png');
          a.download = i18n.t('portal.posterQRCode');
          a.dispatchEvent(event);
        })
        .catch(err => {
          console.log('downloadQrcode error', err);
        });
    };

    const downloadMiniQrcode = () => {
      downloadImagesDirectly(state.appletCodeUrl, i18n.t('自助门户小程序二维码'));
    }


    const updateDoorTypeName = (data) => {
      const { checkList, doorNameLanguage } = data
      state.checkList = checkList
      let language = state.language.filter(v => state.checkList.includes(v.code))
      const isExist = language.some(v => v.code === languageType.value)
      const params = {
        id: doorTypeId.value,
        typeName: data['zh'],
        setting: {
          ...props.doorType.setting,
          doorNameLanguage,
          language,
          defaultLanguage: isExist ? props.doorType?.setting?.defaultLanguage : 'zh'
        }
      }
      editDoorType({ editType: 'update', params });
    }

    function defaultLanguageHandleCommand(data) {
      languageType.value = data
      const params = {
        id: doorTypeId.value,
        setting: {
          ...props.doorType.setting,
          defaultLanguage: data // 匹配不到用户手机语言后使用的默认语言
        }
      }
      editDoorType({ editType: 'update', params });
    }

    // 使用短域名
    function handleUseShortUrl(value) {
      const params = {
        id: doorTypeId.value,
        setting: {
          ...props.doorType.setting,
          isUseShortUrl: value
        }
      }
      editDoorType({ editType: 'update', params });
    }

    function getDoorAppletCode() {
      const domainId = state.shareLink.match(/\/p\/(\d+)/)[1]
      queryDoorAppletCode({ 
        doorTypeId: doorTypeId.value,
        domainId
      }).then(res => {
        if (res.success) {
          state.appletCodeUrl = res.data?.appletCodeUrl ?? '';
        } else {
          state.appletCodeUrl = '';
        }
      })
    }

    onMounted(() => {
      getInitData();
    });

    return {
      ...toRefs(state),
      zh_CN_NAME,
      shareDialog,
      editTemplateNameDialog,
      settingDialog,
      qrcodeImg,
      downloadQrcodeImg,
      handleClickCopyShareUrl,
      handleUseShortUrl,
      doorTypeId,
      isMultiLanguage,
      multiLanguageRef,
      isNoDefaultTemplate,
      handerChange,
      showDialog,
      handleJumpSetting,
      downloadQrcode,
      downloadPoster,
      updateDoorTypeName,
      isHavePortalPageSetAuth,
      shareLinkUrl,
      defaultLanguageSelectList,
      defaultLanguageHandleCommand,
      defaultLanguage,
      downloadMiniQrcode,
      changeUrl,
    };
  },
};
</script>

<style scoped lang='scss'>
@import '../index.scss';

.portal-setting {
  width: 400px;
  height: 100vh;
  background: #ffffff;
  box-sizing: border-box;
  position: relative;
  &-box {
    width: 100%;
    height: calc(100% - 55px);
    overflow-y: auto;
  }

  &-title {
    font-size: 16px;
    font-weight: bold;
    color: rgba(0, 0, 0, 0.65);
  }

  &-header {
    display: flex;
    flex-direction: column;
    padding: 16px 16px 0 16px;

    &-row {
      height: 32px;
      display: flex;
      align-items: center;
      margin-bottom: 6px;

      &-flex {
        flex-basis: 120px;
      }

      &-language {
        flex: 1;
        span:not(:last-child)::after {
          content: '，';
        }
      }

      &-margin {
        margin-right: 5px;
      }

      &-label {
        font-size: 14px;
        color: #595959;
      }
      &-name {
        font-size: 14px;
        color: #262626;
      }

      .icon-edit-fill {
        cursor: pointer;
        color: #8c8c8c;
      }

      &-tip {
        font-size: 14px;
        color: #8c8c8c;
      }

      &-btns {
        width: 389px;
        height: 40px;
        display: flex;
        justify-content: space-between;

        .build {
          flex: 1;
        }

        .setting {
          width: 77px;
        }
      }
    }
    .top {
      display: flex;
      align-items: normal;
      line-height: 22px;
    }
  }

  &-main {
    display: flex;
    flex-direction: column;
    padding: 0px 16px 10px 16px;

    &-view {
      display: flex;
      flex-direction: column;
      margin-bottom: 8px;

      &-title {
        display: flex;
        justify-content: space-between;
        color: rgba(0, 0, 0, 0.65);
        div {
          &:first-child {
            font-size: 16px;
            font-weight: bold;
          }
          &:last-child {
            cursor: pointer;
            color: #13C2C2;
            display: flex;
            align-items: center;
            span {
              margin-left: 3px;
            }
          }
        }
      }

      &-label {
        flex-basis: 85px;
        font-size: 14px;
        color: #595959;
      }

      &-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 16px;

        i {
          margin: 0 15px;
          font-size: 24px;
        }

        .portal-setting-text {
          display: flex;
          flex-direction: column;

          h5 {
            @include font-setting(14px, 400, #262626, 22px);
            margin-bottom: 0;
          }

          span {
            @include font-setting(12px, 400, #8c8c8c, 20px);
          }
        }

        .portal-setting-link {
          @include font-setting(14px, 400, $color-primary-light-6, 20px);
          cursor: pointer;
        }
      }

      &-share {
        display: flex;
        flex-direction: column;
        // justify-content: space-between;
        @include font-setting(14px, 400, #333333, 22px);
         
        .code-wrap {
          display: flex;
          &:last-child {
            margin-top: 16px;
          }
          &-web {
            flex-basis: 85px;
          }
          &-miniApp {
            flex-basis: 85px;
          }
          &-item {
            position: relative;
            display: flex;
            flex-direction: column;
            align-items: center;
            &:hover {
              .mask-wrap {
                opacity: 1;
              }
            }
            .mask-wrap {
              display: flex;
              justify-content: center;
              align-items: center;
              background: rgba(0, 0, 0, 0.5);
              position: absolute;
              left: 0;
              top: 0;
              width: 100%;
              height: 100%;
              opacity: 0;
              transition: opacity 0.6s;
            }

            &-mini {
              img {
                width: 120px;
                height: 120px;
                border-radius: 4px;
                border: 1px solid #e8e8e8;
              }
            }
          }
        }
        #qrcodeImg {
          padding: 4px;
          border-radius: 4px;
          border: 1px solid #e8e8e8;
        }

        .share-qrcodeImg-button {
          width: 80px;
          height: 32px;
          display: flex;
          justify-content: center;
        }
      }

      &-link {
        display: flex;
        color: #333333;
        margin: 20px 0;

        .share-link {
          width: 259px;
          margin-bottom: 8px;
        }
      }

      &-poster {
        display: flex;
        align-items: center;
        &-preview {
          cursor: pointer;
          font-size: 14px;
          color: $color-primary-light-6;
        }
      }
    }
  }

  &-delete {
    position: absolute;
    left: 24px;
    bottom: 24px;
    width: 389px;
    font-size: 14px;

    &-btn {
      width: 389px;
      height: 40px;
    }
  }
}

::v-deep.el-input-group__append,
.el-input-group__prepend {
  border-radius: 0 4px 4px 0;
}
.share-link ::v-deep .el-input__inner {
  width: 200px;
  background: #eeeeee !important;
  color: #bfbfbf !important;
}
.portal-form ::v-deep .el-form-item {
  margin: 0;
}
::v-deep .el-checkbox {
  margin-right: 15px;
}
::v-deep .el-dialog__body{
    padding-right: 52px !important;
 }
.link-btn-wrap {
  display: flex;
  button {
    margin-bottom: 12px;
    max-width: 200px;
    @include text-ellipsis;
  }
}
</style>
